﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Project;
using DWF.Studio.Services;
using DWF.Studio.Share.Log;
using DWF.Studio.Share.Utils;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// WindowPublishProject.xaml 的交互逻辑
    /// </summary>
    public partial class WindowDeployProcess
    {
        private ProjectManager _projectManager = null;

        private IRobotService _robotService = null;

        private IProjectDeployService _projectDeployService = null;

        private ObservableCollection<ProjectNode> _nodeCollection = new ObservableCollection<ProjectNode>();

        private List<ProjectTreeView> buiderProjectTreeViews = null;
        /// <summary>
        /// 
        /// </summary>
        private IConfigService _configService = null;
        private bool isDeploy = false;

        public WindowDeployProcess()
        {
            InitializeComponent();

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            _projectManager = ProjectManager.Instance;
            _robotService = new RobotService();
            _projectDeployService = new ProjectDeployService(_robotService);
            _configService = new ConfigService();
            buiderProjectTreeViews = _projectManager.refreshTreeView();
            
            buiderProjectTreeViews.ForEach(p => _nodeCollection.Add(p));

            var project = _projectManager.CurrentProject;
            if (project != null)
            {
                tbxName.Text = project.Name;
                tbxVersion.Text = project.ProjectVersion;
                tbxDescription.Text = project.Description;
            }

            var isExisting = _robotService.IsExistLocalRobot();
            if (isExisting)
            {
                this.rbtnLocalRobot.IsChecked = true;
            }
            else
            {
                this.rbtnLocalRobot.IsEnabled = false;
                this.rbtnDirectory.IsChecked = true;
            }
            WindowsIdentity current = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
            var isadmin = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);

            if (isadmin)
            {
                this.cbxRequireAdmin.IsChecked = true;
            }
            this.releaseContentTreeView.ItemsSource = _nodeCollection;
        }

        private void RbtnLocalRobot_Checked(object sender, RoutedEventArgs e)
        {
            tbxUsername.IsEnabled = false;
            pwdxPassword.IsEnabled = false;
            tbxUsername.Text = String.Empty;
            pwdxPassword.Clear();
            tbxLocation.IsReadOnly = true;

            btnDirectory.IsEnabled = false;
            tbxLocation.Text = _robotService.GetLocalRobotPath();

            cbxAllowParallel.IsEnabled = true;

            reTextColor();
        }

        private void RbtnDirectory_Checked(object sender, RoutedEventArgs e)
        {
            tbxUsername.IsEnabled = false;
            pwdxPassword.IsEnabled = false;
            tbxUsername.Text = String.Empty;
            pwdxPassword.Clear();
            tbxLocation.IsReadOnly = false;

            btnDirectory.IsEnabled = true;
            tbxLocation.Text = String.Empty;

            cbxAllowParallel.IsEnabled = true;

            reTextColor();
        }
        private void rbtnApplication_Checked(object sender, RoutedEventArgs e)
        {
            tbxUsername.IsEnabled = false;
            pwdxPassword.IsEnabled = false;
            tbxUsername.Text = String.Empty;
            pwdxPassword.Clear();
            tbxLocation.IsReadOnly = false;

            btnDirectory.IsEnabled = true;
            tbxLocation.Text = String.Empty;

            cbxAllowParallel.IsEnabled = false;

            reTextColor();
        }
        private void BtnDirectory_Click(object sender, RoutedEventArgs e)
        {
            VistaFolderBrowserDialog projectDialog = new VistaFolderBrowserDialog();
            var result = projectDialog.ShowDialog(App.Current.MainWindow);

            if (result == true)
            {
                this.tbxLocation.Text = projectDialog.SelectedPath;
            }
        }

        private async void BtnPublish_Click(object sender, RoutedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#EA5050");
            SolidColorBrush brush = new SolidColorBrush(color);
            if (rbtnLocalRobot.IsChecked == true)//机器人
            {
                var targetPath = this.tbxLocation.Text;
                var version = this.tbxVersion.Text;
                var description = this.tbxDescription.Text;
                bool isRegex = Regex.IsMatch(version, "[~!@#$%^&*()=+[\\]{}''\";:/?,><`|！·￥…—（）\\-、；：。，》《 a-z A-Z \u4e00-\u9fa5]");
                
                if (String.IsNullOrWhiteSpace(targetPath) || !FileHelper.CheckFolderExisting(targetPath))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                        Image = MessageBoxImage.Warning,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("WindowDeployProcess_Msg_TargetPath_Error")),
                        Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                    };
                    WpfMessageBox.Show(this, ref msgProperties);

                    Keyboard.Focus(tbxLocation);
                    tbxLocation.BorderBrush = brush;
                    return;
                }
                if (String.IsNullOrWhiteSpace(version) || isRegex|| version.Contains("\\"))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                        Image = MessageBoxImage.Warning,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("WindowDeployProcess_Msg_Verson_Error")),
                        Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                    };
                    WpfMessageBox.Show(this, ref msgProperties);

                    Keyboard.Focus(tbxVersion);
                    tbxVersion.BorderBrush = brush;
                    return;
                }
                try
                {
                    isDeploy = true;
                    WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_WindowDeployProcess_Publish"), this);//显示loading窗体

                    this.btnPublish.IsEnabled = false;

                    var containPackages = cbxContainPackages.IsChecked ?? false;
                    var isCustomContent = this.cbxSetReleaseContent.IsChecked ?? false;
                    var allowParallel = cbxAllowParallel.IsChecked ?? false;
                    var requireAdmin = cbxRequireAdmin.IsChecked ?? false;
                    //生成
                   
                    await _projectDeployService.PublishToRobotAsync(targetPath, version, description, isCustomContent, containPackages, allowParallel, requireAdmin, buiderProjectTreeViews);

                    isDeploy = false;
                    this.DialogResult = true;
                }
                finally
                {
                    isDeploy = false;
                    WindowLoading.CloseWindow();//关闭loading窗体
                    this.btnPublish.IsEnabled = true;
                }
                
            }
            else if (rbtnDirectory.IsChecked == true)//本地目录
            {
                var targetPath = this.tbxLocation.Text;
                var version = this.tbxVersion.Text;
                var description = this.tbxDescription.Text;
                bool isRegex = Regex.IsMatch(version, "[~!@#$%^&*()=+[\\]{}''\";:/?,><`|！·￥…—（）\\-、；：。，》《 a-z A-Z \u4e00-\u9fa5]");

                if (String.IsNullOrWhiteSpace(targetPath) || !FileHelper.CheckFolderExisting(targetPath)|| targetPath.Contains("\\\\"))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                        Image = MessageBoxImage.Warning,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("WindowDeployProcess_Msg_TargetPath_Error")),
                        Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                    };
                    WpfMessageBox.Show(this, ref msgProperties);

                    Keyboard.Focus(tbxLocation);
                    tbxLocation.BorderBrush = brush;
                    return;
                }
                if (String.IsNullOrWhiteSpace(version) || isRegex|| version.Contains("\\"))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                        Image = MessageBoxImage.Warning,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("WindowDeployProcess_Msg_Verson_Error")),
                        Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                    };
                    WpfMessageBox.Show(this, ref msgProperties);

                    Keyboard.Focus(tbxVersion);
                    tbxVersion.BorderBrush = brush;
                    return;
                }

                try
                {
                    isDeploy = true;
                    WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_WindowDeployProcess_Publish"), this);//显示loading窗体

                    this.btnPublish.IsEnabled = false;

                    var containPackages = cbxContainPackages.IsChecked ?? false;
                    var isCustomContent = cbxSetReleaseContent.IsChecked ?? false;
                    var allowParallel = cbxAllowParallel.IsChecked ?? false;
                    var requireAdmin = cbxRequireAdmin.IsChecked ?? false;
                    //生成
                    _projectDeployService.PublishToLocal(targetPath, version, description, isCustomContent, containPackages, allowParallel, requireAdmin, buiderProjectTreeViews);

                    isDeploy = false;
                    this.DialogResult = true;
                }
                finally
                {
                    isDeploy = false;
                    WindowLoading.CloseWindow();//关闭loading窗体
                    this.btnPublish.IsEnabled = true;
                }
            }
            else if (rbtnApplication.IsChecked == true)
            {
                var targetPath = this.tbxLocation.Text;
                var version = this.tbxVersion.Text;
                var description = this.tbxDescription.Text;
                bool isRegex = Regex.IsMatch(version, "[~!@#$%^&*()=+[\\]{}''\";:/?,><`|！·￥…—（）\\-、；：。，》《 a-z A-Z \u4e00-\u9fa5]");

                if (String.IsNullOrWhiteSpace(targetPath) || !FileHelper.CheckFolderExisting(targetPath))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                        Image = MessageBoxImage.Warning,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("WindowDeployProcess_Msg_TargetPath_Error")),
                        Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                    };
                    WpfMessageBox.Show(this, ref msgProperties);

                    Keyboard.Focus(tbxLocation);
                    tbxLocation.BorderBrush = brush;
                    return;
                }

                if (String.IsNullOrWhiteSpace(version) || isRegex|| version.Contains("\\"))
                {
                    var msgProperties = new WpfMessageBoxProperties()
                    {
                        Button = MessageBoxButton.OK,
                        ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                        Image = MessageBoxImage.Warning,
                        Text = string.Format(LocalizationProvider.GetLocalizedString("WindowDeployProcess_Msg_Verson_Error")),
                        Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                    };
                    WpfMessageBox.Show(this, ref msgProperties);

                    Keyboard.Focus(tbxVersion);
                    tbxVersion.BorderBrush = brush;
                    return;
                }

                try
                {
                    isDeploy = true;
                    WindowLoading.ShowWindow(LocalizationProvider.GetLocalizedString("WindowLoading_Msg_WindowDeployProcess_Publish"), this);//显示loading窗体

                    this.btnPublish.IsEnabled = false;

                    var containPackages = cbxContainPackages.IsChecked ?? false;
                    var isCustomContent = cbxSetReleaseContent.IsChecked ?? false;
                    var allowParallel = cbxAllowParallel.IsChecked ?? false;
                    var requireAdmin = cbxRequireAdmin.IsChecked ?? false;
                    //生成
                    _projectDeployService.PublishToApplication(targetPath, version, description, isCustomContent, containPackages, allowParallel, requireAdmin, buiderProjectTreeViews);

                    isDeploy = false;
                    this.DialogResult = true;
                    
                }
                finally
                {
                    isDeploy = false;
                    WindowLoading.CloseWindow();//关闭loading窗体
                    this.btnPublish.IsEnabled = true;
                }
            }
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void tbxVersion_TextChanged(object sender, TextChangedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#BCBCBC");
            SolidColorBrush brush = new SolidColorBrush(color);
            tbxVersion.BorderBrush = brush;
            return;
        }

        private void tbxLocation_TextChanged(object sender, TextChangedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#BCBCBC");
            SolidColorBrush brush = new SolidColorBrush(color);
            tbxLocation.BorderBrush = brush;
            return;
        }

        private void tbxUsername_TextChanged(object sender, TextChangedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#BCBCBC");
            SolidColorBrush brush = new SolidColorBrush(color);
            tbxUsername.BorderBrush = brush;
            return;
        }
        /// <summary>
        /// 选择发布内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxSetReleaseContent_Click(object sender, RoutedEventArgs e)
        {
            if (cbxSetReleaseContent.IsChecked == true)
            {
                popupReleaseContent.IsOpen = false;
                popupReleaseContent.IsOpen = true;
            }
            else
            {
                popupReleaseContent.IsOpen = false;
            }
        }
        private void cbxIsChecked_Click(object sender, RoutedEventArgs e)
        {
            var treeNode = (sender as CheckBox).Parent as StackPanel;
            var projectNode = treeNode.DataContext as ProjectNode;
            if (projectNode.DisplayName == "main.xaml" || projectNode.DisplayName == StaticResource.ProjectSelfFile)
            {
                (sender as CheckBox).IsChecked = true;
                return;
            }
            if (projectNode.NodeType == EProjectNodeType.Folder)
            {
                ProjectTreeView projectTreeView = projectNode as ProjectTreeView;
                var files = buiderProjectTreeViews.FirstOrDefault(o => o.DisplayName == projectTreeView.DisplayName);
                foreach (ProjectTreeViewItem item in files.Children)
                {
                    if (item.DisplayName == "main.xaml")
                    {
                        continue;
                    }
                    item.IsChecked = projectTreeView.IsChecked;
                }
                for (int i = 0; i < buiderProjectTreeViews.Count; i++)
                {
                    if (buiderProjectTreeViews[i].DisplayName == projectNode.DisplayName)
                    {
                        buiderProjectTreeViews[i] = files;
                    }
                }
                _nodeCollection.Clear();
                buiderProjectTreeViews.ForEach(p => _nodeCollection.Add(p));
            }
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            if (isDeploy)
            {
                e.Cancel = true;
            }
        }
        private void reTextColor()
        {
            Color color = (Color)ColorConverter.ConvertFromString("#BCBCBC");
            SolidColorBrush brush = new SolidColorBrush(color);

            tbxUsername.BorderBrush = brush;
            tbxLocation.BorderBrush = brush;
            tbxVersion.BorderBrush = brush;
        }
        private static Boolean IsAdministrator()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }
    }

    public class ValidateModel
    {
        public string Location { get; set; }

        public string Username { get; set; }

        public string Password { get; set; }

        public string Version { get; set; }
    }
    public class PopopHelper
    {
        public static DependencyObject GetPopupPlacementTarget(DependencyObject obj)
        {
            return (DependencyObject)obj.GetValue(PopupPlacementTargetProperty);
        }

        public static void SetPopupPlacementTarget(DependencyObject obj, DependencyObject value)
        {
            obj.SetValue(PopupPlacementTargetProperty, value);
        }

        // Using a DependencyProperty as the backing store for PopupPlacementTarget.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PopupPlacementTargetProperty =
            DependencyProperty.RegisterAttached("PopupPlacementTarget", typeof(DependencyObject), typeof(PopopHelper), new PropertyMetadata(null, OnPopupPlacementTargetChanged));

        private static void OnPopupPlacementTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue != null)
            {
                DependencyObject popupPopupPlacementTarget = e.NewValue as DependencyObject;
                Popup pop = d as Popup;

                Window w = Window.GetWindow(popupPopupPlacementTarget);
                if (null != w)
                {
                    w.LocationChanged += delegate
                    {
                        var offset = pop.HorizontalOffset;
                        pop.HorizontalOffset = offset + 1;
                        pop.HorizontalOffset = offset;
                    };
                }
            }
        }
    }
}
